local server = require "resty.websocket.server"
local cjson = require "cjson"
local auth = require "auth"


-- 创建 websocket 连接
local wb, err = server:new{
    -- timeout = 1200000,
    -- max_payload_len = 65535
}

if not wb then
    ngx.log(ngx.ERR, "failed to new websocket: ", err)
    return ngx.exit(444)
end

-- 进行用户认证
local data, typ, err = wb:recv_frame()
if not data then
    ngx.log(ngx.ERR, "failed to receive frame: ", err)
    return ngx.exit(444)
end

local auth_data = cjson.decode(data)
local user_id, message = auth.login(auth_data.username, auth_data.password)

if not user_id then
    wb:send_text(cjson.encode({success = false, message = message}))
    return ngx.exit(444)
end

wb:send_text(cjson.encode({success = true, user_id = user_id}))

-- 将当前连接添加到客户端列表
_G.clients[tostring(user_id)] = wb
if not _G.clients then
    ngx.log(ngx.ERR, "-----failed clients is null")
    return ngx.exit(444)
end


while true do
    if wb.fatal then
        ngx.log(ngx.ERR, "failed to receive frame: ", err)
        break
    end
    
    local data, typ, err = wb:recv_frame()
    ngx.log(ngx.ERR, "-------------------------", typ, err, data)

    if not data then
        local bytes, err = wb:send_ping()
        if not bytes then
            ngx.log(ngx.ERR, "failed to send ping: ", err)
            break
        end
    elseif typ == "close" then
        break
    elseif typ == "text" then
        for key, value in pairs(_G.clients) do
            ngx.log(ngx.ERR, "------aaaaaa------", key, value == wb)
        end
        local message = cjson.decode(data)
        ngx.log(ngx.ERR, "---------- message: ", data)
        if message.type == "chat" then

            -- 发送消息给接收者
            ngx.log(ngx.ERR, "------aaaaaa------", message.receiver_id)
            local receiver = _G.clients[tostring(message.receiver_id)]
            ngx.log(ngx.ERR, "------xxxxxx------", message.receiver_id)
            if receiver then
                -- local bytes, err = receiver:send_text(cjson.encode(message))
                local bytes, err = receiver:send_text("123456")
                ngx.log(ngx.ERR, "------yyyyyy------", err)
            end
        end
    end
end

-- 客户端断开连接，从列表中移除
-- _G.clients[user_id] = nil
-- wb:send_close()
